// Copyright 2011 Google Inc.  All Rights Reserved.

/**
 * @fileoverview Javascript backing logic for a Chrome extension which redirects
 * HTTP requests to sites which have HTTPS versions to the HTTPS version without
 * leaking HTTP requests.
 * @author danielwh@google.com (Daniel Wagner-Hall)
 */

goog.provide('secureSites.Main');

goog.require('secureSites.SecureProber');
goog.require('secureSites.TriState');
goog.require('secureSites.constants');

secureSites.Main = function(secureProber) {
  this.secureProber = secureProber || new secureSites.SecureProber();
};

/**
 * Hooks in Chrome extension API webRequest listeners.
  */
secureSites.Main.prototype.hookInitialListeners = function() {
  var self = this;
  chrome.experimental.webRequest.onBeforeRequest.addListener(
    function(details) { return self.onBeforeRequestFilter(self, details); }, secureSites.constants.HTTP_ONLY_REQUEST_FILTER, secureSites.constants.BLOCKING_EXTRA_INFO_SPEC);
};

/**
 * Returns a response indicating whether a particular request should be altered.
 * @param {!{requestId: !string, url: !string, method: !string, tabId: ?number, type: !string, timeStamp: !number}} details
 * @return {!Object} Object denoting any alteration to take place.
  */
secureSites.Main.prototype.onBeforeRequestFilter = function(self, details) {
  /** @const */ var url = details.url;
  var exists = self.secureProber.secureVersionExistsFor(url);
  var toReturn = exists == secureSites.TriState.TRUE ?
      {redirectUrl: secureSites.secureVersionOf(url)} : {};
  return toReturn;
};
